import datetime
import requests
from loguru import logger

headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
    "baggage": "sentry-environment=production,sentry-public_key=9b4a6569c04148aa9ab275932e8b1961,sentry-trace_id=6d3c87b36e644447aa41b966f7c05994",
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded",
    "origin": "https://online.seranking.com",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://online.seranking.com/admin.site.rankings.site_id-7535981.html?ref=left_menu_clicked",
    "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "sentry-trace": "6d3c87b36e644447aa41b966f7c05994-883ed211bb97959d",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
    "x-requested-with": "XMLHttpRequest"
}

def get_100_keys_id(matching_project, cookies):
    current_date = datetime.datetime.now()
    current_date_str = current_date.strftime("%Y-%m-%d")
    yesterday_date = current_date - datetime.timedelta(days=1)
    yesterday_str = yesterday_date.strftime("%Y-%m-%d")
    url = "https://online.seranking.com/api.projects.site.positions.html"
    params = {
        "do": "getKeywordsIds",
        "site_id": matching_project['site_id'],
        "columns[]": "created_at",
        "keywords_count_display": "100",
        "page": "1",
        "group_by": "list",
        "sort_by": "name",
        "sort_mode": "1",
        "is_paid": "0",
        "columns_group_mode": "day",
        "site_se_id": matching_project['site_se_id'],
        "list_type": "not_in_serp",
        "report_period_from": yesterday_str,
        "report_period_to": current_date_str
    }
    res = requests.get(url, params=params, cookies=cookies, headers=headers)
    if res.status_code == 200:
        data = res.json()
        keys_word_id = data['data']
        keys_list = keys_word_id.split(',')
        logger.info(f"{matching_project['company_name']} -----> 获取关键崔id成功: 共有{len(keys_list)}个关键词")
        return keys_word_id